﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Newtonsoft.Json;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Input;
using Wpf.Ui.Controls;
using 充电桩上位机.Model.PTAConfig;

namespace 充电桩上位机.ViewModel.CommonRegisters;

public class CommonRegistersManagementViewModel : ObservableObject
{
    [Category("界面配置选择")]
    private CommonRegDataWith _selRegItem = new();
    public CommonRegDataWith SelRegItem
    {
        get => _selRegItem;
        set {
            DataSaveName = value.filename ?? string.Empty;
            SetProperty(ref _selRegItem, value); 
        }
    }
    public class CommonRegDataWith
    {
        public string? filename { get; set; }
        public string? filedirectory{ get; set; }
    }

    [Category("界面配置表")]
    private ObservableCollection<CommonRegDataWith> _regItems = new();
    public ObservableCollection<CommonRegDataWith> RegItems
    {
        get => _regItems;
        set => SetProperty(ref _regItems, value);
    }

    [Category("本地配置导入按钮")]
    public ICommand ImportCommand =>
    new RelayCommand(async () => await ImportCommandFunc());
    public async Task ImportCommandFunc()
    {
        string json = File.ReadAllText(SelRegItem.filedirectory!);
        MainWindowViewModel.pTAConfigModel = JsonConvert.DeserializeObject<PTAConfigModel>(json)!;
        var uiMessageBox = new MessageBox
        {
            Title = "PTA配置",
            Content =
        "   配置导入成功，请切换页面. ",
        };
        var result = await uiMessageBox.ShowDialogAsync();
    }
    [Category("本地配置导出名称")]
    private string _dataSaveName = string.Empty;
    public string DataSaveName
    {
        get => _dataSaveName;
        set {
            string pattern = @"[\\/:*?""<>|]";
            string sanitizedFileName = Regex.Replace(value, pattern, "");
            SetProperty(ref _dataSaveName, sanitizedFileName); 
        }
    }
    [Category("寄存器配置表")]
    private string _selecting_Registers_Items = string.Empty;
    public string Selecting_Registers_Items
    {
        get => _selecting_Registers_Items;
        set => SetProperty(ref _selecting_Registers_Items, value);
    }
    [Category("导入配置")]
    private string _importText = string.Empty;
    public string ImportText
    {
        get => _importText;
        set => SetProperty(ref _importText, value);
    }
    [Category("导出配置命名")]
    private string _enterSavePTAName = string.Empty;
    public string EnterSavePTAName
    {
        get => _enterSavePTAName;
        set => SetProperty(ref _enterSavePTAName, value);
    }
    [Category("导出配置命名")]
    private string _saveText = string.Empty;
    public string SaveText
    {
        get => _saveText;
        set => SetProperty(ref _saveText, value);
    }
    [Category("标题名称")]
    private string _common_Registers_Management = string.Empty;
    public string Common_Registers_Management
    {
        get => _common_Registers_Management;
        set => SetProperty(ref _common_Registers_Management, value);
    }
    [Category("本地配置导出内容")]
    public ICommand SaveCommand =>
    new RelayCommand(async () => await SaveCommandFunc());
    public async Task SaveCommandFunc()
    {
        //名称一样则会进行覆盖操作
        // 将对象序列化为 JSON 字符串
        if (!string.IsNullOrEmpty(DataSaveName))
        {
            string _appStartupPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)!;

            string jsonString = JsonConvert.SerializeObject(MainWindowViewModel.pTAConfigModel, Formatting.Indented);
            // 定义文件路径

            string filePath = new(Path.Combine
                            (_appStartupPath!, "PTAConfig", $"{DataSaveName}.json"));
            // 将 JSON 字符串写入文件
            File.WriteAllText(filePath, jsonString);
            var uiMessageBox = new MessageBox
            {
                Title = "PTA配置",
                Content =
                    "   配置写入成功. ",
            };
            var result = await uiMessageBox.ShowDialogAsync();
        }
    }

    public CommonRegistersManagementViewModel()
    {
        string _appStartupPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)!;
        string savepath = new(Path.Combine
                        (_appStartupPath!, "PTAConfig"));

        Selecting_Registers_Items = MainWindowViewModel.SetLanguage(MainWindowViewModel.globellanguage, "Selecting Registers Items");
        ImportText = MainWindowViewModel.SetLanguage(MainWindowViewModel.globellanguage, "Import");
        EnterSavePTAName = MainWindowViewModel.SetLanguage(MainWindowViewModel.globellanguage, "Enter a Registers item name");
        SaveText = MainWindowViewModel.SetLanguage(MainWindowViewModel.globellanguage, "Save");
        Common_Registers_Management = MainWindowViewModel.SetLanguage(MainWindowViewModel.globellanguage, "Common Registers Management");
        if (Directory.Exists(savepath))
        {
            var filr = Directory.GetFiles(savepath);

            foreach (var ft in filr)
            {
                RegItems.Add(new CommonRegDataWith
                {
                    filename = Path.GetFileNameWithoutExtension(ft),
                    filedirectory = ft
                });
            }
        }
        else
        {
            Directory.CreateDirectory(savepath);
        }
    }
}
